package com.cy.server;

import com.cy.utils.HttpProtocolUtil;
import com.cy.utils.StaticResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author ChenYan
 * @Date 2021/8/13 13:42
 * @Description Response 输出静态资源
 */
public class Response {

    private OutputStream outputStream;

    public Response(OutputStream outputStream){
        this.outputStream = outputStream;
    }

    /**
     * 根据路径返回Html
     * @param path
     */
    public void outputHtml(String path) throws IOException {
        //获取静态资源的绝对路径
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(path);

        //输出静态资源
        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()){
            //输出
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        }
        else {
            //输出404
            output(HttpProtocolUtil.getHttpHeader404());
        }
    }


    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }

}
